import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { loginApi, getUserInfoApi } from '../api/user/user'
import type { LoginParams, UserInfo } from '../api/user/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const loading = ref<boolean>(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value?.username || '')
  const roles = computed(() => userInfo.value?.roles || [])
  const avatar = computed(() => userInfo.value?.avatar || '')

  // 初始化token（从localStorage读取）
  const initToken = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
    }
  }

  // 登录方法
  const login = async (loginParams: LoginParams): Promise<boolean> => {
    loading.value = true
    try {
      const response = await loginApi(loginParams)
      
      if (response.code === 200 && response.data.token) {
        // 保存token
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        
        ElMessage.success('登录成功！')
        return true
      } else {
        ElMessage.error(response.data.message || '登录失败')
        return false
      }
    } catch (error) {
      console.error('登录请求失败:', error)
      ElMessage.error('网络错误，请稍后重试')
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async (): Promise<boolean> => {
    if (!token.value) {
      ElMessage.warning('请先登录')
      return false
    }

    try {
      const response = await getUserInfoApi()
      if (response.code === 200 && response.data.checkUser) {
        userInfo.value = response.data.checkUser
        return true
      } else {
        ElMessage.error('获取用户信息失败')
        logout()
        return false
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败')
      logout()
      return false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    ElMessage.success('已退出登录')
  }

  // 清除所有状态
  const reset = () => {
    token.value = ''
    userInfo.value = null
    loading.value = false
    localStorage.removeItem('token')
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 计算属性
    isLoggedIn,
    username,
    roles,
    avatar,
    
    // 方法
    initToken,
    login,
    getUserInfo,
    logout,
    reset
  }
})
